package com.qiqichangting.changting.utils;

import com.qiqichangting.changting.pojo.Data;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;

public class JDUtils {

    public static List<Data> JDJsoup(String keyword, int page) throws IOException {
        File file = new File("E:"+File.separator+"text"+File.separator+"测试3.xlsx");
        if (!file.exists()){
            file.createNewFile();
        }
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("凄凄长亭");
        Row row = sheet.createRow(0);
        Cell imgs = row.createCell(0);
        imgs.setCellValue("图片链接");
        Cell prices = row.createCell(1);
        prices.setCellValue("价格");
        Cell names = row.createCell(2);
        names.setCellValue("名称");
        Cell shops = row.createCell(3);
        shops.setCellValue("出品方");
        int i = 0;
        int avg = 0;
        for (int pages = 1; pages <=page ; pages++) {
            String url = "https://search.jd.com/Search?keyword="+keyword+"&page="+pages;
            //通过jsoup获取页面对象
            Document document = Jsoup.parse(new URL(url), 30000);
            //解析网页获取网页中的指定div信息
            Element element = document.getElementById("J_goodsList");
            //获得里面li标签
            Elements li = element.getElementsByTag("li");
            System.out.println(element);
            for (Element el : li) {
                i+=1;
                String img = el.getElementsByTag("img").eq(0).attr("src");
                String price = el.getElementsByClass("p-price").eq(0).text();
                String name = el.getElementsByClass("p-name").eq(0).text();
                String shop = el.getElementsByClass("p-shop").eq(0).text();
                Row row1 = sheet.createRow(i);
                Cell cell = row1.createCell(avg);
                cell.setCellValue(img);
                Cell cell1 = row1.createCell(avg+1);
                cell1.setCellValue(price);
                Cell cell2 = row1.createCell(avg+2);
                cell2.setCellValue(name);
                Cell cell3 = row1.createCell(avg+3);
                cell3.setCellValue(shop);
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                workbook.write(fileOutputStream);
                fileOutputStream.close();
            }

        }
        return null;
    }
}